<template>
  <div class="shelf-box">
    <div class="user-info">
      <div class="info-left">
        <div class="info-top">
          <span>{{userInfo.email}}</span>
          <span>收藏: {{bookList.length}}本</span>
        </div>
        <div class="info-bottom">
          <span>后退</span>
        </div>
      </div>
      <div class="info-right">
        <el-avatar
          :src="avatar"
          style="height:96px;width:96px;border:3px solid rgba(255,255,255,1)"
        ></el-avatar>
      </div>
    </div>
    <div class="main-box">
      <div class="filter-box">
        <el-tabs v-model="activeName" @tab-click="handleClick">
          <el-tab-pane label="我的书库" name="shelf">
            <div class="shelf-list" v-if="sliceBookList.length > 0">
              <el-checkbox-group v-model="delBookList" v-show="editFlag">
                <el-checkbox
                  v-for="(item, index) in sliceBookList"
                  :key="index"
                  :label="item.book_shelf_id"
                >
                  <shelfcard
                    :is_edit="true"
                    :image="item.image"
                    :is_over="item.is_over"
                    :type="item.type"
                    :name="item.name"
                    :writer="item.writer"
                    :new_chapter="item.new_chapter"
                    @handleToRead="handleToRead(item.book_id,item.last_read_chapter)"
                  />
                </el-checkbox>
              </el-checkbox-group>
              <shelfcard
                v-show="!editFlag"
                v-for="(item, index) in sliceBookList"
                :key="index"
                :image="item.image"
                :is_over="item.is_over"
                :type="item.type"
                :name="item.name"
                :writer="item.writer"
                :new_chapter="item.new_chapter"
                @handleToRead="handleToRead(item.book_id,item.last_read_chapter)"
              />
            </div>
            <div v-else class="content">
              <h1>咦!还未添加任何书籍!</h1>
              <h2>快去书库逛逛看吧~</h2>
              <el-image
                fit="contain"
                src="https://wpimg.wallstcn.com/007ef517-bafd-4066-aae4-6883632d9646"
              ></el-image>
            </div>
            <div class="page">
              <el-pagination
                @current-change="handleCurrentChange"
                :current-page.sync="currentPage"
                :page-size="pageSize"
                hide-on-single-page
                layout="prev, pager, next, jumper"
                :total="listTotal"
              ></el-pagination>
            </div>
          </el-tab-pane>
          <el-tab-pane label="浏览历史" name="history">
            <div v-if="historyList.length > 0" class="history-box">
              <div class="history-title">浏览历史</div>
              <div
                v-for="(item,index) in historyList"
                :key="index"
                class="history-item"
                @click="handleToRead(item.id,item.chapter_id)"
              >
                <span class="history-name">{{item.name}}</span>
                <span class="history-writer">{{item.writer}} 著</span>
                <span class="history-type">{{item.type}}</span>
                <span class="history-over">{{item.is_over}}</span>
                <span class="history-time">{{item.last_read_time}}</span>
              </div>
            </div>
            <div v-else class="content">
              <h1>咦!还未看过任何书籍!</h1>
              <h2>快去书库逛逛看吧~</h2>
              <el-image
                fit="contain"
                src="https://wpimg.wallstcn.com/007ef517-bafd-4066-aae4-6883632d9646"
              ></el-image>
            </div>
          </el-tab-pane>
        </el-tabs>
        <div class="shelf-edit" v-if="bookList.length > 0">
          <span v-show="!editFlag && activeName =='shelf'" @click="handleToEdit">编辑</span>
          <div class="edit-box" v-show="editFlag && activeName =='shelf'">
            <span @click="handleToCheckAll">{{checkAllFlag ? '取消全选':'全选'}}</span>
            <span @click="handleToDelete">删除</span>
            <span @click="handleToEdit">完成</span>
          </div>
          <span
            v-show="historyList.length > 0 && activeName =='history'"
            @click="handleToClearHistory"
          >清空</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import { bookShelfList, delBookShelf } from "@/api/shelf";
import { getChapterDetail } from "@/api/chapter";
import shelfcard from "@/components/ShelfCard";
export default {
  name: "shelf",
  components: { shelfcard },
  data() {
    return {
      activeName: "shelf",
      bookList: [],
      historyList: [],
      editFlag: false,
      checkAllFlag: false,
      delBookList: [],
      currentPage: 1,
      listTotal: 1,
      pageSize: 10,
    };
  },
  computed: {
    ...mapGetters(["loginStatus", "avatar", "userInfo"]),
    sliceBookList() {
      return this.bookList.slice(
        (this.currentPage - 1) * this.pageSize,
        this.currentPage * this.pageSize
      );
    },
  },
  watch: {
    loginStatus(val) {
      if (!val) {
        this.$router.push("/homepage");
      }
    },
    delBookList(val) {
      if (val.length == 0) {
        this.checkAllFlag = false;
      } else {
        this.checkAllFlag = true;
      }
    },
    bookList(val) {
      this.listTotal = val.length;
    },
  },
  created() {
    if (this.$route.query.type) {
      this.activeName = this.$route.query.type;
    }
    this.getShelfList();
    this.getHistoryList();
  },
  methods: {
    handleCurrentChange() {
      window.scrollTo({ top: 0 });
    },
    handleClick(tab, event) {
      console.log(tab, event);
    },
    getShelfList() {
      const headers = {
        Authorization: `Bearer ${this.$store.state.user.token}`,
      };
      bookShelfList(headers).then((res) => {
        this.bookList = res.data.bookList;
      });
    },
    handleToRead(id, chapter_id) {
      this.$router.push({
        path: "/read",
        query: { id, chapter_id },
      });
    },
    handleToEdit() {
      this.editFlag = !this.editFlag;
    },
    handleToDelete() {
      if (this.delBookList.length == 0) {
        this.$message.error("未选择任何书籍");
      } else {
        this.$alert(
          `确认要删除这${this.delBookList.length}本书籍`,
          "删除书籍",
          {
            confirmButtonText: "确定",
            callback: (action) => {
              if (action == "confirm") {
                const headers = {
                  Authorization: `Bearer ${this.$store.state.user.token}`,
                };
                let bookShelfId = this.delBookList.join(",");
                delBookShelf({ bookShelfId }, headers).then((res) => {
                  if (res.code == 200) {
                    this.$message({
                      type: "success",
                      message: res.msg,
                    });
                    this.editFlag = false;
                    this.getShelfList();
                  }
                });
              }
            },
          }
        );
      }
    },
    handleToCheckAll() {
      if (this.checkAllFlag) {
        this.delBookList = [];
      } else {
        let _delBookList = [];
        this.bookList.forEach((item) => {
          _delBookList.push(item.book_shelf_id);
        });
        this.delBookList = _delBookList;
      }
    },
    getHistoryList() {
      if (window.localStorage.getItem("recently_read")) {
        let recently_read = JSON.parse(
          window.localStorage.getItem("recently_read")
        );
        if (recently_read.length != 0) {
          recently_read.forEach((item) => {
            getChapterDetail({ id: item.id }).then((res) => {
              this.historyList.push({
                id: item.id,
                chapter_id: item.chapterId,
                name: res.data.name,
                writer: res.data.writer,
                type: res.data.type,
                is_over: res.data.is_over,
                last_read_time: item.lastReadTime,
              });
            });
          });
        }
      }
    },
    handleToClearHistory() {
      this.$alert(`确认要清空阅读历史`, "清空阅读历史", {
        confirmButtonText: "确定",
        callback: (action) => {
          if (action == "confirm") {
            this.historyList = [];
            window.localStorage.setItem("recently_read", "");
            this.$message({
              message: "清空阅读历史成功",
              type: "success",
            });
          }
        },
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.shelf-box {
  width: 1200px;
  margin: 0 auto;
  padding-top: 72px;
  .user-info {
    width: 1200px;
    height: 150px;
    background: rgba(0, 38, 107, 1);
    box-shadow: 0px 14px 56px 0px rgba(0, 49, 137, 0.32);
    border-radius: 12px;
    display: flex;
    align-items: flex-start;
    justify-content: space-between;
    padding: 27px 32px;
    margin-bottom: 48px;
    .info-left {
      color: rgba(255, 255, 255, 1);
      display: flex;
      flex-direction: column;
      align-items: flex-start;
      width: 988px;
      .info-top {
        display: flex;
        flex-direction: column;
        align-items: flex-start;
        border-bottom: 1px solid rgba(243, 247, 254, 0.3);
        width: 988px;
        span:first-child {
          font-size: 24px;
          line-height: 24px;
          font-family: Microsoft YaHei;
          font-weight: bold;
          margin-bottom: 9px;
        }
        span:last-child {
          font-size: 14px;
          font-family: Microsoft YaHei;
          font-weight: 600;
          color: rgba(255, 255, 255, 0.85);
          margin-bottom: 24px;
        }
      }
      .info-bottom {
        margin-top: 15px;
        font-size: 12px;
        font-family: Microsoft YaHei;
        font-weight: 600;
        color: rgba(255, 255, 255, 0.85);
      }
    }
    .info-right {
    }
  }
  .main-box {
    width: 1200px;
    .filter-box {
      position: relative;
      .shelf-list {
        display: flex;
        flex-wrap: wrap;
        justify-content: space-between;
      }
      .shelf-edit {
        font-size: 14px;
        position: absolute;
        top: 35px;
        right: 25px;
        span {
          cursor: pointer;
          &:hover {
            color: #92c8ff;
          }
        }
        .edit-box {
          span {
            padding: 0 0 0 22px;
            position: relative;
            &::after {
              content: "";
              width: 2px;
              height: 4px;
              border: 1px solid rgba(24, 46, 94, 0.25);
              position: absolute;
              top: 7px;
              right: -12px;
            }
          }
          span:last-child {
            &::after {
              border: none;
            }
          }
        }
      }
      .page {
        margin: 50px 0 120px 0;
      }
      .history-box {
        width: 1190px;
        background: rgba(255, 255, 255, 1);
        border-radius: 12px;
        padding: 36px 36px 30px 30px;
        margin: 15px 5px 100px 5px;
        &:hover {
          transform: translateY(-3px);
          transition: all 0.3s linear;
          box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
        }
        .history-title {
          font-size: 20px;
          font-family: Microsoft YaHei;
          font-weight: 600;
          color: rgba(6, 27, 65, 0.65);
          line-height: 24px;
          text-align: left;
          margin-bottom: 44px;
        }
        .history-item {
          width: 100%;
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 24px 10px;
          border-bottom: 1px solid rgba(6, 27, 65, 0.05);
          cursor: pointer;
          span {
            display: inline-block;
            font-size: 14px;
            font-family: Microsoft YaHei;
            font-weight: 400;
            color: rgba(6, 27, 65, 0.45);
            line-height: 22px;
          }
          .history-name {
            width: 50%;
            display: flex;
            justify-content: flex-start;
          }
          .history-writer {
            width: 10%;
            display: flex;
            justify-content: flex-start;
          }
          .history-type {
            display: flex;
            justify-content: flex-start;
          }
          .history-over {
          }
          .history-time {
          }
        }
      }
    }
  }
}
</style>